package com.ozner.cup.Device.WaterPurifier.RoWifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ozner.WaterPurifier.RoWifi.WaterPurifier_RO_WIFI;
import com.ozner.cup.Base.WebActivity;
import com.ozner.cup.Bean.Contacts;
import com.ozner.cup.Command.OznerPreference;
import com.ozner.cup.CupRecord;
import com.ozner.cup.DBHelper.DBManager;
import com.ozner.cup.DBHelper.UserInfo;
import com.ozner.cup.Device.DeviceFragment;
import com.ozner.cup.Device.TDSSensorManager;
import com.ozner.cup.Device.WaterPurifier.SetupWaterActivity;
import com.ozner.cup.Device.WaterPurifier.WaterTDSActivity;
import com.ozner.cup.R;
import com.ozner.cup.UIView.PurifierDetailProgress;
import com.ozner.cup.Utils.LCLogUtils;
import com.ozner.cup.Utils.WeChatUrlUtil;
import com.ozner.device.BaseDeviceIO;
import com.ozner.device.OznerDevice;
import com.ozner.device.OznerDeviceManager;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static com.ozner.device.BaseDeviceIO.ACTION_DEVICE_CONNECTED;


/**
 * description: WPRoWifiFragment 厨下式水芯片wifi版
 * autour: ozner_67
 * date: 2017/8/2 14:12
 * e-mail: xinde.zhang@cftcn.com
 */
public class WPRoWifiFragment extends DeviceFragment {
    private static final String TAG = "WPRoWifiFragment";
    private static final int TextSize = 40;
    private static final int NumSize = 50;

    @InjectView(R.id.iv_filter_icon)
    ImageView ivFilterIcon;
    @InjectView(R.id.tv_filter_value)
    TextView tvFilterValue;
    @InjectView(R.id.tv_filter_tips)
    TextView tvFilterTips;
    @InjectView(R.id.rlay_filter)
    RelativeLayout rlayFilter;
    @InjectView(R.id.iv_setting)
    ImageView ivSetting;
    @InjectView(R.id.rlay_bottom)
    RelativeLayout rlayBottom;
    //    @InjectView(tv_ozner_days)
//    TextView tvOznerDays;
    @InjectView(R.id.iv_deviceConnectIcon)
    ImageView ivDeviceConnectIcon;
    @InjectView(R.id.tv_deviceConnectTips)
    TextView tvDeviceConnectTips;
    @InjectView(R.id.llay_deviceConnectTip)
    LinearLayout llayDeviceConnectTip;
    @InjectView(R.id.waterProgress)
    PurifierDetailProgress waterProgress;
    @InjectView(R.id.iv_tdsStateIcon)
    ImageView ivTdsStateIcon;
    @InjectView(R.id.tv_tdsStateText)
    TextView tvTdsStateText;
    @InjectView(R.id.llay_tdsState)
    LinearLayout llayTdsState;
    @InjectView(R.id.tv_preValue)
    TextView tvPreValue;
    @InjectView(R.id.tv_spec)
    TextView tvSpec;
    @InjectView(R.id.tv_afterValue)
    TextView tvAfterValue;
    @InjectView(R.id.lay_tdsValue)
    LinearLayout layTdsValue;
    @InjectView(R.id.tv_tdsTips)
    TextView tvTdsTips;
    @InjectView(R.id.llay_tdsTips)
    LinearLayout llayTdsTips;
//    @InjectView(R.id.llay_tds_detail)
//    LinearLayout llayTdsDetail;
//    @InjectView(R.id.tv_powerswitch)
//    TextView tvPowerswitch;
//    @InjectView(R.id.iv_powerswitch)
//    ImageView ivPowerswitch;
//    @InjectView(R.id.rlay_powerswitch)
//    RelativeLayout rlayPowerswitch;
//    @InjectView(R.id.tv_hotswitch)
//    TextView tvHotswitch;
//    @InjectView(R.id.iv_hotswitch)
//    ImageView ivHotswitch;
//    @InjectView(R.id.rlay_hotswitch)
//    RelativeLayout rlayHotswitch;
//    @InjectView(R.id.rl_hot)
//    RelativeLayout rlHot;
//    @InjectView(R.id.tv_coolswitch)
//    TextView tvCoolswitch;
//    @InjectView(R.id.iv_coolswitch)
//    ImageView ivCoolswitch;
//    @InjectView(R.id.rlay_coolswitch)
//    RelativeLayout rlayCoolswitch;
//    @InjectView(R.id.rl_cool)
//    RelativeLayout rlCool;

    private ROMonitor mMonitor;
    private TDSSensorManager tdsSensorManager;
    String address;
    private int oldPreValue, oldThenValue;
    private WaterPurifier_RO_WIFI mWaterPurifier;
    private int filter_A_Time;
    private int filter_B_Time;
    private int filter_C_Time;

    public WPRoWifiFragment() {
        // Required empty public constructor
    }

    public static WPRoWifiFragment newInstance(String mac) {
        Bundle args = new Bundle();
        args.putString(DeviceFragment.DeviceAddress, mac);
        WPRoWifiFragment fragment = new WPRoWifiFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        tdsSensorManager = new TDSSensorManager(getContext());
        initAnimation();
        try {
            Bundle bundle = getArguments();
            address = bundle.getString(DeviceFragment.DeviceAddress);
            oldPreValue = oldThenValue = 0;
            mWaterPurifier = (WaterPurifier_RO_WIFI) OznerDeviceManager.Instance().getDevice(address);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(TAG, "onCreate_Ex: " + ex.getMessage());
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_water_ro_wifi, container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void setDevice(OznerDevice device) {
        oldPreValue = oldThenValue = 0;
        if (mWaterPurifier != null) {
            if (mWaterPurifier.Address() != device.Address()) {
                mWaterPurifier = null;
                mWaterPurifier = (WaterPurifier_RO_WIFI) device;
                refreshUIData();
            }
        } else {
            mWaterPurifier = (WaterPurifier_RO_WIFI) device;
            refreshUIData();
        }
    }

    @Override
    public void onResume() {
        registerMonitor();
        refreshUIData();
        super.onResume();
    }

    @Override
    public void onPause() {
        releaseMonitor();
        super.onPause();
    }

    /**
     * 注册广播监听
     */
    private void registerMonitor() {
        mMonitor = new ROMonitor();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DEVICE_CONNECTED);
        filter.addAction(BaseDeviceIO.ACTION_DEVICE_CONNECTING);
        filter.addAction(BaseDeviceIO.ACTION_DEVICE_DISCONNECTED);
        filter.addAction(OznerDeviceManager.ACTION_OZNER_MANAGER_DEVICE_CHANGE);
        filter.addAction(OznerDevice.ACTION_DEVICE_UPDATE);
        getContext().registerReceiver(mMonitor, filter);
    }

    /**
     * 注销广播监听
     */
    private void releaseMonitor() {
        if (isWaterPuriferAdd()) {
            getContext().unregisterReceiver(mMonitor);
        }
    }

    @Override
    protected void refreshUIData() {
        if (isWaterPuriferAdd()) {
            if (mWaterPurifier != null && mWaterPurifier.connectStatus() == BaseDeviceIO.ConnectStatus.Connected) {
                showTdsState();
                loadFilterInfo();
            } else {
                loadDisconnectView();
            }
        }
    }

    /**
     *
     */
    private void loadDisconnectView() {
        tvPreValue.setText(R.string.state_null);
        tvAfterValue.setText(R.string.state_null);
        tvPreValue.setTextSize(TextSize);
        tvAfterValue.setTextSize(TextSize);
        ivTdsStateIcon.setVisibility(View.GONE);
        tvTdsStateText.setText(R.string.state_null);
        waterProgress.update(0, 0);
        tvFilterValue.setText(getResources().getString(R.string.state_null));
        tvFilterTips.setText(R.string.filter_status);
        rlayFilter.setEnabled(false);
    }

    /**
     *
     */
    private void loadFilterInfo() {
        filter_A_Time = Math.round(mWaterPurifier.deviceInfo().filterAPercent);
        filter_B_Time = Math.round(mWaterPurifier.deviceInfo().filterBPercent);
        filter_C_Time = Math.round(mWaterPurifier.deviceInfo().filterCPercent);
        int filterValue = Math.min(filter_C_Time, Math.min(filter_A_Time, filter_B_Time));
        LCLogUtils.E(TAG, "loadFilterInfo:A:" + filter_A_Time + ",B:" + filter_B_Time + ",C:" + filter_C_Time + ",Min:" + filterValue);
        setFilterState(filterValue);
    }


    /**
     * 显示滤芯百分比
     *
     * @param fitPre
     */
    private void setFilterState(final int fitPre) {
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
        if (isWaterPuriferAdd()) {
            int tempPre = fitPre;
            if (tempPre > 100) {
                tempPre = 100;
            }
            if (tempPre < 0) {
                tempPre = 0;
            }
            rlayFilter.setEnabled(true);
            tvFilterValue.setText(tempPre + "%");
            if (0 == tempPre) {
                tvFilterTips.setText(R.string.filter_need_change);
                ivFilterIcon.setImageResource(R.drawable.filter_state0);
                told();
            } else if (tempPre > 0 && tempPre <= 10) {
                tvFilterTips.setText(R.string.filter_need_change);
                ivFilterIcon.setImageResource(R.drawable.filter_state1);
                //ro水机一级页面的滤芯提醒
                told();
            } else if (tempPre > 10 && tempPre <= 60) {
                tvFilterTips.setText(R.string.filter_status);
                ivFilterIcon.setImageResource(R.drawable.filter_state2);
            } else {
                tvFilterTips.setText(R.string.filter_status);
                ivFilterIcon.setImageResource(R.drawable.filter_state3);
            }

        }
//            }
//        });
    }

    private void told() {
        new AlertDialog.Builder(getContext())
                .setMessage(getString(R.string.filter_need_change))
                .setPositiveButton(getString(R.string.buy_filter), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        buyFilter();
                        dialog.dismiss();
                    }
                }).setNegativeButton(getString(R.string.I_got_it), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    private void buyFilter() {
        String userId = OznerPreference.GetValue(getContext(), OznerPreference.UserId, "");
        if (userId != null) {
            UserInfo userInfo = DBManager.getInstance(getContext()).getUserInfo(userId);
            String usertoken = OznerPreference.getUserToken(getContext());
            String shopUrl = WeChatUrlUtil.getMallUrl(userInfo.getMobile(), usertoken, "zh", "zh");
            startWebActivity(shopUrl);
        }

    }

    private void startWebActivity(String url) {
        Intent filterIntent = new Intent(getActivity(), WebActivity.class);
        filterIntent.putExtra(Contacts.PARMS_URL, url);
        startActivity(filterIntent);
    }

    /**
     * 是否已添加到View
     *
     * @return
     */
    private boolean isWaterPuriferAdd() {
        return !WPRoWifiFragment.this.isRemoving() && !WPRoWifiFragment.this.isDetached() && WPRoWifiFragment.this.isAdded();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    /**
     * 处理TDS显示相关
     */
    private void showTdsState() {
        int tdsPre, tdsThen;
        if (mWaterPurifier.roWifiStatus().TDS1 > 0 && mWaterPurifier.roWifiStatus().TDS2 > 0
                && mWaterPurifier.roWifiStatus().TDS1 != 65535 && mWaterPurifier.roWifiStatus().TDS2 != 65535) {
            //TDS值比较大的作为净化前的值
            if (mWaterPurifier.roWifiStatus().TDS1 > mWaterPurifier.roWifiStatus().TDS2) {
                tdsPre = mWaterPurifier.roWifiStatus().TDS1;
                tdsThen = mWaterPurifier.roWifiStatus().TDS2;
            } else {
                tdsPre = mWaterPurifier.roWifiStatus().TDS2;
                tdsThen = mWaterPurifier.roWifiStatus().TDS1;
            }
        } else {
            //有任何一个不大于0或者有任何一个为65535，就全部置为0
            tdsPre = tdsThen = 0;
        }

        if (tdsThen > 99) {
            tdsThen = 99;
        }
        Log.e(TAG, "showTdsState: oldPre:" + oldPreValue + " , oldThen:" + oldThenValue);
        //只有当数据和上次不一样时才更新刷新
        if (oldPreValue != tdsPre || oldThenValue != tdsThen) {
            oldPreValue = tdsPre;
            oldThenValue = tdsThen;
            //净化前后的值都不为0，并且都不为65535
            if (tdsPre != 0) {
                tvPreValue.setText(String.valueOf(tdsPre));
                tvAfterValue.setText(String.valueOf(tdsThen));
                tvPreValue.setTextSize(NumSize);
                tvAfterValue.setTextSize(NumSize);
                updateTdsSensor(String.valueOf(tdsThen), String.valueOf(tdsPre));
            } else {
                tvPreValue.setText(R.string.state_null);
                tvAfterValue.setText(R.string.state_null);
                tvPreValue.setTextSize(TextSize);
                tvAfterValue.setTextSize(TextSize);
            }
            // 根据净化后的tds显示状态
            showTdsStateTips(tdsThen);
            if (tdsPre > 250) {
                tdsPre = 250;
            }
            if (tdsThen > 250) {
                tdsThen = 250;
            }
            waterProgress.update(Math.round((tdsPre / 250f) * 100), Math.round((tdsThen / 250f) * 100));
        }
    }

    /**
     * 根据净化后的tds显示状态
     */
    private void showTdsStateTips(int thenTds) {
        if (thenTds > 0) {
            ivTdsStateIcon.setVisibility(View.VISIBLE);
            llayTdsTips.setVisibility(View.VISIBLE);
        } else {
            llayTdsTips.setVisibility(View.INVISIBLE);
        }
        if (thenTds == 0) {
            ivTdsStateIcon.setVisibility(View.GONE);
            tvTdsStateText.setText(R.string.state_null);
        } else if (thenTds > 0 && thenTds <= CupRecord.TDS_Good_Value) {
            if (!this.isDetached())
                Glide.with(this).load(R.drawable.face_good).into(ivTdsStateIcon);
            tvTdsStateText.setText(R.string.health);
        } else if (thenTds > CupRecord.TDS_Good_Value && thenTds < CupRecord.TDS_Bad_Value) {
            if (!this.isDetached()) {
                Glide.with(this).load(R.drawable.face_soso).into(ivTdsStateIcon);
            }
            tvTdsStateText.setText(R.string.soso);
        } else if (thenTds > CupRecord.TDS_Bad_Value) {
            if (!this.isDetached()) {
                Glide.with(this).load(R.drawable.face_bad).into(ivTdsStateIcon);
            }
            tvTdsStateText.setText(R.string.bad);
        }
    }

    /**
     * 上传TDS
     *
     * @param tds
     * @param beforeTds
     */
    private void updateTdsSensor(String tds, String beforeTds) {
        if (mWaterPurifier != null) {
            tdsSensorManager.updateTds(mWaterPurifier.Address(), mWaterPurifier.Type(), tds, beforeTds, "", null);
        }
    }

    @OnClick({R.id.rlay_filter, R.id.iv_setting, R.id.llay_tds_detail, R.id.rlay_powerswitch,
            R.id.rlay_hotswitch, R.id.rlay_coolswitch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rlay_filter:
                if (mWaterPurifier != null) {
                    Intent filterIntent = new Intent(getContext(), ROWifiFilterStatusActivity.class);
                    filterIntent.putExtra(Contacts.PARMS_MAC, mWaterPurifier.Address());
                    filterIntent.putExtra(ROWifiFilterStatusActivity.PARMS_FILTER_A, filter_A_Time);
                    filterIntent.putExtra(ROWifiFilterStatusActivity.PARMS_FILTER_B, filter_B_Time);
                    filterIntent.putExtra(ROWifiFilterStatusActivity.PARMS_FILTER_C, filter_C_Time);
                    startActivity(filterIntent);
                } else {
                    showCenterToast(R.string.Not_found_device);
                }
                break;
            case R.id.iv_setting:
                if (mWaterPurifier != null) {
                    Intent setupIntent = new Intent(getContext(), SetupWaterActivity.class);
                    setupIntent.putExtra(Contacts.PARMS_MAC, mWaterPurifier.Address());
                    setupIntent.putExtra(Contacts.PARMS_URL, Contacts.aboutRo);
                    startActivity(setupIntent);
                } else {
                    showCenterToast(R.string.Not_found_device);
                }
                break;
            case R.id.llay_tds_detail:
                if (mWaterPurifier != null) {
                    Intent tdsIntent = new Intent(getContext(), WaterTDSActivity.class);
                    tdsIntent.putExtra(Contacts.PARMS_MAC, mWaterPurifier.Address());
                    startActivity(tdsIntent);
                } else {
                    showCenterToast(R.string.Not_found_device);
                }
                break;
            case R.id.rlay_powerswitch:
                showCenterToast(R.string.no_available);
                break;
            case R.id.rlay_hotswitch:
                showCenterToast(R.string.no_available);
                break;
            case R.id.rlay_coolswitch:
                showCenterToast(R.string.no_available);
                break;
        }
    }


    class ROMonitor extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshUIData();
        }
    }
}
